import { ControlContextMenuItem } from '../../../../entity/control-context-menu';
import { DgControl } from '../../../../utils/dg-control';
import { ContextMenuManager } from '../../../../service/context-menu.manager';
import { MultiViewManageService } from '../property/services/multi-view-manage.service';
import FdContainerBaseComponent from '../../common/containerBase/containerBase';
import { contextMenu, MultiViewItemContextMenu } from './context-menu-config';
import { cloneDeep } from 'lodash-es';
import { RowNode } from '@farris/ui-treetable';
import { MessagerService } from '@farris/ui-messager';
import { ControlTreeNode } from '@farris/designer-devkit';

const CREATE_MULTIVIEW_ITEM = 'createMultiViewItem';
const REMOVE_MULTIVIEW_ITEM = 'removeMultiViewItem';

export class MultiViewContainerContextMenuManager extends ContextMenuManager {

    private itemManageService: MultiViewManageService;
    private msgService: MessagerService;

    /** 标识父级节点，用于右键点击多视图某一项 */
    private parentRowNode: RowNode;

    constructor(cmp: FdContainerBaseComponent, rowNode: RowNode, parentRowNode: RowNode) {
        super(cmp, rowNode);

        this.parentRowNode = parentRowNode;
        this.itemManageService = this.injector.get(MultiViewManageService);
        this.msgService = this.injector.get(MessagerService);
    }
    /**
     * 过滤、修改控件树右键菜单
     */
    setContextMenuConfig() {


        let menuConfig = cloneDeep(contextMenu) as ControlContextMenuItem[];

        const parentTreeNode = this.parentRowNode && this.parentRowNode.node as ControlTreeNode;
        if (parentTreeNode && parentTreeNode.rawElement.type === DgControl.MultiViewContainer.type) {
            menuConfig = cloneDeep(MultiViewItemContextMenu) as ControlContextMenuItem[];
        }


        if (!menuConfig) {
            return [];
        }

        menuConfig = this.assembleCreateMultiViewItemMenu(menuConfig);

        // 配置菜单点击事件
        this.addContextMenuHandle(menuConfig);

        return menuConfig;
    }
    /**
     * 点击控件树右键菜单
     */
    contextMenuClicked(e: { data: RowNode, menu: ControlContextMenuItem }) {

        const menu = e.menu;

        if (menu.parentMenuId === CREATE_MULTIVIEW_ITEM) {
            this.createMultiViewItem(menu.id);
            return;
        }
        if (menu.id === REMOVE_MULTIVIEW_ITEM) {

            this.removeMultiViewItem();
            return;
        }
        this.notifyService.warning('暂不支持');
    }

    private assembleCreateMultiViewItemMenu(menuConfig: ControlContextMenuItem[]) {
        const currentViewItems = this.cmpInstance.component.contents || [];
        this.itemManageService.initViewTypes(this.cmpInstance.component.dataSource, currentViewItems);

        const viewTypeOptions = this.itemManageService.viewTypeOptions;

        const createViewMenu = menuConfig.find(menu => menu.id === CREATE_MULTIVIEW_ITEM);
        if (!createViewMenu) {
            return menuConfig;
        }
        createViewMenu.children = [];

        viewTypeOptions.forEach(option => {
            createViewMenu.children.push({
                title: option.name,
                id: option.id
            });
        });

        return menuConfig;
    }
    /**
     * 控件树选择多视图节点右键添加视图
     * @param menuId 添加的视图类型
     */
    private createMultiViewItem(menuId: string) {
        const currentViewItems = this.cmpInstance.component.contents || [];
        this.itemManageService.createMultiViewItem(menuId, currentViewItems).subscribe(viewItem => {

            // 向DOM中添加Component和ViewModel 节点
            Object.keys(this.itemManageService.createdComponent).forEach(componentId => {
                const { component, viewModel } = this.itemManageService.createdComponent[componentId];
                this.domService.addComponent(component);
                this.domService.addViewModel(viewModel);
            });

            const multiViewElement = this.cmpInstance.component;
            multiViewElement.contents.push(viewItem);

            // 更新视图切换图标
            const parentTreeNode = this.rowNode.parent as ControlTreeNode;

            const parentContainer = parentTreeNode.rawElement;
            this.itemManageService.updateViewChangeButtons(multiViewElement.contents, multiViewElement.viewChangeBar, parentContainer, this.cmpInstance.componentId);

            this.notifyService.success('添加成功');
            this.refreshFormService.refreshFormDesigner.next();
        });
    }

    /**
     * 控件树选择某一视图项右键进行移除
     */
    removeMultiViewItem() {

        const multiViewElement = this.cmpInstance.component;
        if (multiViewElement.contents.length === 1) {
            this.notifyService.warning('不允许移除唯一的视图');
            return;
        }
        let viewItem;
        let viewItemIndex;
        if (multiViewElement.contents) {
            viewItemIndex = multiViewElement.contents.findIndex(c => c.id === this.rowNode.id);
            viewItem = multiViewElement.contents[viewItemIndex];
        }
        if (!viewItem) {
            return;
        }

        this.msgService.question('确认移除【' + viewItem.title + '】视图?', () => {

            multiViewElement.contents.splice(viewItemIndex, 1);

            // 从记录的新增交叉表视图中移除
            if (viewItem.viewType === 'CrosstabView' && this.itemManageService.newCrosstabViewIds.includes(viewItem.id)) {
                this.itemManageService.newCrosstabViewIds = this.itemManageService.newCrosstabViewIds.filter(id => id !== viewItem.id);
            }

            // 移除的视图若是默认视图，需要修改默认视图
            if (multiViewElement.defaultType === viewItem.id) {
                multiViewElement.defaultType = multiViewElement.contents[0] && multiViewElement.contents[0].id;
            }
            // 移除的视图若是当前显示视图，需要修改默认视图
            if (multiViewElement.currentTypeInDesignerView === viewItem.id) {
                multiViewElement.currentTypeInDesignerView = multiViewElement.defaultType;
            }
            // 更新视图切换图标
            const parentTreeNode = this.rowNode.parent.parent as ControlTreeNode;
            const parentContainer = parentTreeNode.rawElement;
            this.itemManageService.updateViewChangeButtons(multiViewElement.contents, multiViewElement.viewChangeBar, parentContainer, this.cmpInstance.componentId);

            // 同步移除dom中涉及的component和viewModel
            const cmpRef = this.domService.selectNode(viewItem, item => item.type === DgControl.ComponentRef.type);
            if (cmpRef) {
                const cmp = this.domService.getComponentById(cmpRef.component);
                if (cmp) {
                    this.domService.deleteComponent(cmpRef.component);
                    this.domService.deleteViewModelById(cmp.viewModel);
                }
            }


            this.notifyService.success('移除成功');
            this.refreshFormService.refreshFormDesigner.next();
        });
    }
}

